/*************************************************************************
 * File Name:    Binary_Tree_Maximum_Path_Sum.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: Fri 01 Nov 2013 11:54:31 PM CST
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Binary Tree Maximum Path Sum
 |
 | Given a binary tree, find the maximum path sum.
 | The path may start and end at any node in the tree.
 |
 | For example:
 | Given the below binary tree,
 |    1
 |   / \
 |  2   3
 | Return 6.
 |-----------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <iomanip>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode *root)
    {
        if (root == NULL) return 0;
        
        int ans = root->val;
        dfs(root, ans);
        return ans;
    }
    
    int dfs(TreeNode *root, int &ans)
    {
        if (root == NULL) return 0;
        int left_val = dfs(root->left, ans);
        int right_val = dfs(root->right, ans);
        
        if (left_val < 0) left_val = 0;
        if (right_val < 0) right_val = 0;
        
        if (left_val + root->val + right_val > ans) {
            ans = left_val + root->val + right_val;
        }
        return max(left_val, right_val) + root->val;
    }
};
